package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.AliP2PUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.huoshan.CVProcessUtil;
import com.ruoyi.common.utils.keling.KeLingRequest;
import com.ruoyi.common.utils.keling.KeLingUtil;
import com.ruoyi.system.domain.GenerationPicTimes;
import com.ruoyi.system.domain.KelingPic;
import com.ruoyi.system.mapper.KelingPicMapper;
import com.ruoyi.system.service.IKelingPicService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 可灵生成记录Service业务层处理
 *
 * @author ruoyi
 * @date 2024-11-01
 */
@Service
public class KelingPicServiceImpl implements IKelingPicService {
    @Resource
    private KelingPicMapper kelingPicMapper;

    /**
     * 查询可灵生成记录
     *
     * @param kelingId 可灵生成记录主键
     * @return 可灵生成记录
     */
    @Override
    public KelingPic selectKelingPicByKelingId(Long kelingId) {
        return kelingPicMapper.selectKelingPicByKelingId(kelingId);
    }

    /**
     * 查询可灵生成记录列表
     *
     * @param kelingPic 可灵生成记录
     * @return 可灵生成记录
     */
    @Override
    public List<KelingPic> selectKelingPicList(KelingPic kelingPic) {
        return kelingPicMapper.selectKelingPicList(kelingPic);
    }

    /**
     * 新增可灵生成记录
     *
     * @param kelingPic 可灵生成记录
     * @return 结果
     */
    @Override
    public int insertKelingPic(KelingPic kelingPic) {
        kelingPic.setCreateTime(DateUtils.getNowDate());
        return kelingPicMapper.insertKelingPic(kelingPic);
    }

    /**
     * 修改可灵生成记录
     *
     * @param kelingPic 可灵生成记录
     * @return 结果
     */
    @Override
    public int updateKelingPic(KelingPic kelingPic) {
        kelingPic.setUpdateTime(DateUtils.getNowDate());
        return kelingPicMapper.updateKelingPic(kelingPic);
    }

    /**
     * 批量删除可灵生成记录
     *
     * @param kelingIds 需要删除的可灵生成记录主键
     * @return 结果
     */
    @Override
    public int deleteKelingPicByKelingIds(String kelingIds) {
        return kelingPicMapper.deleteKelingPicByKelingIds(Convert.toStrArray(kelingIds));
    }

    /**
     * 删除可灵生成记录信息
     *
     * @param kelingId 可灵生成记录主键
     * @return 结果
     */
    @Override
    public int deleteKelingPicByKelingId(Long kelingId) {
        return kelingPicMapper.deleteKelingPicByKelingId(kelingId);
    }

    private static boolean isImageFile(String name) {
        String lowerCaseName = name.toLowerCase();
        return lowerCaseName.endsWith(".jpg") || lowerCaseName.endsWith(".jpeg") ||
                lowerCaseName.endsWith(".png") || lowerCaseName.endsWith(".gif");
    }

    @Override
    public AjaxResult generations(String path, String prompt,String negativePrompt, Integer number, Double fidelity,Integer count) throws Exception {
        List<GenerationPicTimes> timesList = kelingPicMapper.findGenerationPicTimes(count);
        List<String> pathTimes = timesList.stream().map(GenerationPicTimes::getFileName).collect(Collectors.toList());
        KeLingUtil keLingUtil = new KeLingUtil();
        keLingUtil.getInstance();
//        File folder = new File(path); // 替换为你的图片文件夹路径
//        File[] listOfFiles = folder.listFiles();
//        for (File file : listOfFiles) {
        Path rootPath = Paths.get(path);
        final String[] porm = {prompt};
        Files.walk(rootPath)
                .filter(Files::isRegularFile) // 过滤出普通文件
                .forEach(targetPath -> {
                    File file = targetPath.toFile();
                    if (file.isFile() && isImageFile(file.getName())) {
                        String prompts = "";
                        if (!pathTimes.contains(file.getName())) {
                            KeLingRequest req = new KeLingRequest();
                            if (targetPath.toString().contains("Object_3k")) {
                                String parentPathName = targetPath.getParent().getParent().getFileName().toString();
                                if (StringUtils.isNotEmpty(parentPathName)) {
                                    String keyWord = parentPathName.split("_")[1];
                                    if (StringUtils.isNotEmpty(keyWord)) {
                                        prompts = prompt.replaceAll("object", keyWord);
                                    }
                                }
                            } else {
                                prompts = prompt;
                            }
                            req.setPrompt(prompts);
                            req.setImage(targetPath.toString());
                            req.setNumber(number);
                            req.setFidelity(fidelity);
//                            AliP2PUtil text2Image = new AliP2PUtil();
//                            int keywordIndex = targetPath.toString().indexOf("Object_3k");
//                            String zPath = targetPath.toString().substring(keywordIndex);
//                            String taskId = text2Image.createAsyncTask(prompts,zPath);

                            String taskId = keLingUtil.generations(req);
                            if (StringUtils.isEmpty(taskId) || taskId.equals("欠费")) {
                                return;
                            }
                            KelingPic pic = new KelingPic();
                            pic.setCount(number);
                            pic.setPath(targetPath.toString());
                            pic.setTaskId(taskId);
                            pic.setIsUpload(1);
                            pic.setPrompt(prompts);
                            pic.setFileName(file.getName());
                            pic.setFidelity(String.valueOf(fidelity));
                            kelingPicMapper.insertKelingPic(pic);
                            try {
                                Thread.sleep(10000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
//        }

        return AjaxResult.success("成功");
    }

    @Override
    public AjaxResult menuMaking(String path, String prompt, Integer number, Double fidelity,Integer count) throws Exception {
        List<GenerationPicTimes> timesList = kelingPicMapper.findGenerationPicTimes(count);
        List<String> pathTimes = timesList.stream().map(GenerationPicTimes::getFileName).collect(Collectors.toList());
        KeLingUtil keLingUtil = new KeLingUtil();
        keLingUtil.getInstance();
        Path rootPath = Paths.get(path);
        Files.walk(rootPath)
                .filter(Files::isRegularFile) // 过滤出普通文件
                .forEach(targetPath -> {
                    File file = targetPath.toFile();
                    if (file.isFile() && isImageFile(file.getName())) {
                        if (!pathTimes.contains(file.getName())) {
                            KeLingRequest req = new KeLingRequest();
                            String promptStr = "";
                            promptStr = prompt+","+getMenuMakingPrompt(prompt,targetPath.toString());
                            req.setPrompt(promptStr);
                            req.setImage(targetPath.toString());
                            req.setNumber(number);
                            req.setFidelity(fidelity);
                            String taskId = keLingUtil.generations(req);
                            if (StringUtils.isEmpty(taskId) || taskId.equals("欠费")) {
                                return;
                            }
                            KelingPic pic = new KelingPic();
                            pic.setCount(number);
                            pic.setPath(targetPath.toString());
                            pic.setTaskId(taskId);
                            pic.setIsUpload(1);
                            pic.setPrompt(promptStr);
                            pic.setFileName(file.getName());
                            pic.setFidelity(String.valueOf(fidelity));
                            kelingPicMapper.insertKelingPic(pic);
                            try {
                                Thread.sleep(5000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
//        }

        return AjaxResult.success("成功");
    }

   private String  getMenuMakingPrompt(String prompt,String picPath)  {
       String result = "";
       try {

           //pic 路径转txt路径
           String txtPath = "";
           if(picPath.contains("png")){
               txtPath = picPath.replace("png","txt");
           }else if(picPath.contains("jpg")){
               txtPath = picPath.replace("jpg","txt");
           }else if(picPath.contains("jpeg")){
               txtPath = picPath.replace("jpeg","txt");
           }

           File txtfile = new File(txtPath);
           BufferedReader reader = new BufferedReader(new FileReader(txtfile));
           StringBuilder sb = new StringBuilder();
           String line;
           List<String> stringList = Lists.newArrayList();
           while ((line = reader.readLine()) != null) {
               sb.append(line).append("\n");
               if (StringUtils.isNotEmpty(line) && !"\n".equals(line)) {
                   stringList.add(line);
               }

           }
           reader.close();
           String content = sb.toString();
           String zhAnalysis = content.replaceAll("\n", "");
           if (StringUtils.isNotEmpty(zhAnalysis) && !zhAnalysis.equals("null")) {
               if(picPath.contains("中文")){
                   result = stringList.get(1);
               }else if(picPath.contains("英文")){
                   result = stringList.get(0);
               }

           }

       }catch (Exception e){
           e.printStackTrace();
       }

        return result;
   }

    @Override
    public AjaxResult saveDownPic(String picStyle) {

        KelingPic kelingPic = new KelingPic();
        kelingPic.setIsUpload(1);
        List<KelingPic> kelingPicList = kelingPicMapper.selectKelingPicList(kelingPic);
        String fileExtension = ".jpg"; // 文件扩展名

//        KeLingUtil keLingUtil = new KeLingUtil();
//        keLingUtil.getInstance();
//
//            if (CollectionUtils.isNotEmpty(kelingPicList)) {
//                for (KelingPic pic : kelingPicList) {
//                    //专为实物3000另换盘符
//                    String newDriveLetter = "E"; // 新的驱动器字母
//                    // 创建原始路径对象
//                    Path original = Paths.get(pic.getPath());
//                    // 创建新的路径
//                    Path newPath = Paths.get(newDriveLetter + original.toString().substring(1));
//                    File file = new File(newPath.toString());
//                    String fileName = FileUtils.getNameNotSuffix(pic.getPath());
//                    fileName = fileName + "_" + picStyle; // 自定义文件名
//                    String parentPath = file.getParent();
//                    String saveDir = parentPath;
//                    keLingUtil.downloadImage(pic.getRemark(), saveDir, fileName, fileExtension);
//                    pic.setDownCount(1);
//                    pic.setIsUpload(0);
//                    kelingPicMapper.updateKelingPic(pic);
//                }
//
//            }




        KeLingUtil keLingUtil = new KeLingUtil();
        keLingUtil.getInstance();
        for (KelingPic pic : kelingPicList) {
            Map<String, List<String>> allData = keLingUtil.queryByTaskId(pic.getTaskId());
            List<String> urlList = allData.get(pic.getTaskId());
            if (CollectionUtils.isNotEmpty(urlList)) {
                for (String url : urlList) {
                    //专为实物3000另换盘符
                    String newDriveLetter = "E"; // 新的驱动器字母
                    // 创建原始路径对象
                    Path original = Paths.get(pic.getPath());
                    // 创建新的路径
                    Path newPath = Paths.get(newDriveLetter + original.toString().substring(1));
                    File file = new File(newPath.toString());
                    String fileName = FileUtils.getNameNotSuffix(pic.getPath());
                    if(StringUtils.isNotEmpty(picStyle)){
                        fileName = fileName + "_" + picStyle; // 自定义文件名
                    }
                    String parentPath = file.getParent();
                    String saveDir = parentPath;
                    keLingUtil.downloadImage(url, saveDir, fileName, fileExtension);
                }
                pic.setDownCount(urlList.size());
                pic.setIsUpload(0);
            }

            kelingPicMapper.updateKelingPic(pic);
        }
        return AjaxResult.success("成功");
    }

    @Override
    public AjaxResult jiMengGenerations(String path, String prompt, Double fidelity, Integer count,String picStyle) throws Exception {
        List<GenerationPicTimes> timesList = kelingPicMapper.findGenerationPicTimes(count);
        List<String> pathTimes = timesList.stream().map(GenerationPicTimes::getFileName).collect(Collectors.toList());
        Path rootPath = Paths.get(path);
        Files.walk(rootPath)
                .filter(Files::isRegularFile) // 过滤出普通文件
                .forEach(targetPath -> {
                    File file = targetPath.toFile();
                    if (file.isFile() && isImageFile(file.getName())) {
                        String prompts = "";

                            KeLingRequest req = new KeLingRequest();
                            if (targetPath.toString().contains("Object_3k")) {
                                String parentPathName = targetPath.getParent().getFileName().toString();
                                if (StringUtils.isNotEmpty(parentPathName)) {
                                    String keyWord = parentPathName.split("_")[1];
                                    if (StringUtils.isNotEmpty(keyWord)) {
                                        prompts = prompt.replaceAll("object", keyWord);
                                    }
                                }
                            } else {
                                prompts = prompt;
                            }
                        if (!pathTimes.contains(file.getName())) {
                           for(int i=0;i<count;i++){
                             String url=  CVProcessUtil.generations(targetPath.toString(),prompts,picStyle,fidelity);
                               KelingPic pic = new KelingPic();
                               pic.setCount(1);
                               pic.setPath(targetPath.toString());
                               pic.setRemark(url);
                               pic.setIsUpload(1);
                               pic.setPrompt(prompts);
                               pic.setFileName(file.getName());
                               pic.setFidelity(String.valueOf(fidelity));
                               kelingPicMapper.insertKelingPic(pic);
                           }
                        }else{
                            for(GenerationPicTimes gtimes:timesList){
                                if(gtimes.getFileName().equals(file.getName())&&gtimes.getTimes()<count){
                                    int newCount = count - gtimes.getTimes();
                                    for(int i=0;i<newCount;i++){
                                        String url=  CVProcessUtil.generations(targetPath.toString(),prompts,picStyle,fidelity);
                                        KelingPic pic = new KelingPic();
                                        pic.setCount(1);
                                        pic.setPath(targetPath.toString());
                                        pic.setRemark(url);
                                        pic.setIsUpload(1);
                                        pic.setPrompt(prompts);
                                        pic.setFileName(file.getName());
                                        pic.setFidelity(String.valueOf(fidelity));
                                        kelingPicMapper.insertKelingPic(pic);
                                    }
                                }

                            }
                        }
                    }
                });
        return null;
    }

}
